import { reactive, ref } from "vue";
import { defineStore } from "pinia";
import { reqLoginByPhone, reqUpdateAvatarAndName, reqUserInfoByToken, requestLoginByCode } from "@/api/api-user";
import { DEFAULT_USER_INFO } from "@/static/constants/user-constants";
import { setToken } from "@/utils/token";
import { reqUploadImage } from "@/api/api-others";
import { navigateTo } from "@/utils/navigate";
import { showToast } from "@/utils/tools";

export const useUser = defineStore("user", () => {

  //#region 用户信息相关
  /** 用户信息 */
  const userInfo = ref<UserInfo>(DEFAULT_USER_INFO);
  /** 邀请人用户id */
  const invitorUserId = ref('');

  /** 设置邀请人用户id */
  const setInvitorUserId = (id: string) => {
    invitorUserId.value = id;
  }

  /** 从res中提取并设置用户信息 */
  const setUserInfo = (res: any) => {
    // 从res中提取用户信息
    const { wx_headimg: avatar, wx_name: name, userId: id, phone, zfb_name, zfb_account, money_remain, money_all, vip_end_time } = res.data.data.userInfo
    // 如果不为undefined，则设置对应的值
    userInfo.value.avatar = avatar || userInfo.value.avatar;
    userInfo.value.name = name || userInfo.value.name;
    userInfo.value.id = id || userInfo.value.id;
    userInfo.value.phone = phone || userInfo.value.phone;
    userInfo.value.zfb_name = zfb_name || userInfo.value.zfb_name;
    userInfo.value.zfb_account = zfb_account || userInfo.value.zfb_account;
    userInfo.value.money_remain = String(Number(money_remain).toFixed(2)) || userInfo.value.money_remain;
    userInfo.value.money_all = String(Number(money_all).toFixed(2)) || userInfo.value.money_all;
    userInfo.value.vip_end_time = vip_end_time || userInfo.value.vip_end_time;
    userInfo.value.useNum = String(res.data.data.useNum || '0') || userInfo.value.vip_end_time;

    /** 集中判断用户是否为VIP */
    if (!userInfo.value.vip_end_time) {
      userInfo.value.isVip = false
    } else {
      const vip_end_time = userInfo.value.vip_end_time + ' 23:59:59';
      const endTime = new Date(vip_end_time).getTime();
      const nowDate = Date.now();
      userInfo.value.isVip =  ((endTime - nowDate) >= 0)
    }
  }

  /** 获取用户信息 */
  const getUserInfo = async () => {
    const res: any = await reqUserInfoByToken();
    setUserInfo(res);
  }

  /**
   * 上传并修改用户头像和昵称
   * @param temAvatarPath 临时头像路径
   */
  const uploadAvatarAndName = async (temAvatarPath: string) => {
    let avatarPath = userInfo.value.avatar

    if (temAvatarPath) {
      let uploadRes: any = null;
      // 上传头像
      uploadRes = await reqUploadImage(temAvatarPath)
      avatarPath = JSON.parse(uploadRes.data).data.filePath
    }

    // 修改用户信息
    const updateRes: any = await reqUpdateAvatarAndName(
      avatarPath,
      userInfo.value.name,
      invitorUserId.value
    );
    console.log('updateRes', updateRes)

    userInfo.value.avatar = avatarPath
  }

  //#endregion

  //#region 登录、注册、登出相关

  /**
   * 静默登录（使用uni.login返回的code登录）
   */
  const silenceLogin = async () => {
    try {
      const uniLoginRes: any = await uni.login();
      const loginByCodeRes: any = await requestLoginByCode(uniLoginRes.code);
      // 设置用户信息
      setUserInfo(loginByCodeRes);
      // 设置token
      const data = loginByCodeRes.data.data;
      setToken(data.token);
    } catch (e) {
      console.error('loginByCode error', e);
    }
  };

  /**
   * 检查是否有手机号、头像、昵称，没有则跳转到对应页面进行注册
   * @params params 跳转到注册页面时要携带的参数
   * @returns 是否有手机号、头像、昵称
   */
  const checkUserInfo = (routeQuery: AnyObject = {}) => {
    console.log('checkUserInfo', userInfo.value)
    // 判断是否有手机号
    if (!userInfo.value.phone) {
      showToast('您暂未登录，请先登录')
      setTimeout(() => {
        navigateTo('login', routeQuery)
      }, 1000)
      return false
    }

    // 判断是否有头像昵称
    if (!userInfo.value.avatar || !userInfo.value.name) {
      const route = getCurrentPages()[0].route
      // 如果不在上传信息页面，则跳转到上传信息页面
      if (route !== 'subpkg/upload-information') {
        showToast('您暂未登录，请先登录')
        setTimeout(() => {
          navigateTo('upload-information', routeQuery)
        }, 1000)
        return false
      }
    }

    return true
  }

  /**
   * 手机号登录
   * @param code 授权手机号的code
   */
  const loginByPhone = async (code: string) => {
    try {
      const res: any = await reqLoginByPhone(code);
      console.log('loginByPhone res', res)
      setUserInfo(res);
    } catch (e) {
      console.error('loginByPhone error', e)
    }
  }

  /** 用户登出 */
  const logout = () => {
    userInfo.value = DEFAULT_USER_INFO;
  };

  //#endregion

  /**
   * 绑定支付宝后，更新用户的支付宝账户、支付宝姓名等信息
   * @param zfb_account 支付宝账户（手机号）
   * @param zfb_name 支付宝姓名
   */
  const updateZfbInfo = (zfb_account: string, zfb_name: string) => {
    userInfo.value.zfb_account = zfb_account;
    userInfo.value.zfb_name = zfb_name;
  }

  /**
   * 提现后，更新账户余额
   */
  const updateUserMoney = (money: string) => {
    const take = Number(money);
    if (Number(userInfo.value.money_all)) {
      userInfo.value.money_all = String((Number(userInfo.value.money_all) + take).toFixed(2));
    } else {
      userInfo.value.money_all = String(take.toFixed(2));
    }
    if (Number(userInfo.value.money_remain)) {
      userInfo.value.money_remain = String((Number(userInfo.value.money_remain) - take).toFixed(2));
    } else {
      userInfo.value.money_remain = String(take.toFixed(2));
    }
  }

  /** 用户邀请的VIP用户和非VIP用户 */
  const invitedVipUser = reactive<InvitedUser[]>([]);
  const invitedCommonUser = reactive<InvitedUser[]>([]);

  /** 更新邀请到的Vip用户列表 */
  const updateInvitedVipUser = (res: any) => {
    invitedVipUser.splice(0)
    res.forEach((item: any, index: number) => {
      
      const { headImg, name, income, create_time, money } = item;
      invitedVipUser.push({
        id: String(index + 1),
        name,
        avatar: headImg,
        income,
        time: create_time || '',
        money: money || '',
      })
    });
  }
  /** 更新邀请到的非VIP用户列表 */
  const updateInvitedCommonUser = (res: any) => {
    invitedCommonUser.splice(0)
    res.forEach((item: any, index: number) => {
      
      const { headImg, name, create_time } = item;
      invitedCommonUser.push({
        id: String(index + 1),
        name,
        avatar: headImg,
        time: create_time || ''
      })
    });
  }

  return {
    userInfo,
    invitorUserId,
    invitedVipUser,
    invitedCommonUser,
    setInvitorUserId,
    getUserInfo,
    uploadAvatarAndName,
    silenceLogin,
    checkUserInfo,
    loginByPhone,
    logout,
    updateZfbInfo,
    updateUserMoney,
    updateInvitedVipUser,
    updateInvitedCommonUser,
  };
});
